/*
 * Copyright 2009 Jesse McLaughlin (nzjess@gmail.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.travelfusion.xmlclient.test.support;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.travelfusion.xmlclient.login.Login;
import org.travelfusion.xmlclient.transport.TfXTransport;
import org.travelfusion.xmlclient.xobject.XRequest;

import com.google.inject.Singleton;
import com.mycila.xmltool.XMLDoc;
import com.mycila.xmltool.XMLTag;

/**
 * @author Jesse McLaughlin (nzjess@gmail.com)
 */
@Singleton
public class EchoTransport implements TfXTransport {

  private boolean loginRequired = true;

  private Login login = null;

  public void setLoginRequired(boolean loginRequired) {
    this.loginRequired = loginRequired;
  }

  public void setLogin(Login login) {
    this.login = login;
  }

  @Send
  public InputStream send(XRequest request, String requestString) throws IOException {
    XMLTag doc = XMLDoc.from(requestString, true);
    if (login != null) {
      validateLogin(doc, login.getXmlLoginId(), "XmlLoginId");
      validateLogin(doc, login.getLoginId(), "LoginId");
    }
    return new ByteArrayInputStream(requestString.getBytes("UTF-8"));
  }

  private void validateLogin(XMLTag doc, String loginId, String loginTagName) {
    if (!doc.gotoRoot().gotoChild().hasTag(loginTagName)) {
      if (loginRequired) throw new IllegalStateException("missing login tag");
      else return;
    }
    if (!loginId.equals(doc.gotoChild(loginTagName).getText())) {
      throw new IllegalStateException("invalid login id");
    }
  }
}
